from apps.forms import BaseForm
from wtforms import validators,StringField
from  wtforms.validators import Length,InputRequired,regexp
import hashlib

#telephone
#timestamp
#sign

class SMSCaptchaForm(BaseForm):
    salt = 'dfsdiokl;j5462{!@#$2345tdfsas'
    telephone = StringField(validators=[regexp(r'1[345789]\d{9}')])
    timestamp = StringField(validators=[regexp(r'\d{13}')])
    sign = StringField(validators=[InputRequired()])
    #重写验证器
    def validate(self):
        #首先进行父类的验证，如果父类都过不了，那就直接返回FALSE
        result = super(SMSCaptchaForm, self).validate()
        if not result:
            return False
        #如果父类的验证通过，再进行下面的验证
        #这三条数据应该都是从前台拿到的数据
        telephone = self.telephone.data
        timestamp = self.timestamp.data
        sign = self.sign.data
        # 前台传递过来的sign值和后台生成的sign2 判断是否相等，用同样的算法加密
        sign2 = hashlib.md5((timestamp+telephone+self.salt).encode('utf-8')).hexdigest()
        print('sign:' ,sign)
        print('sign2:' ,sign2)
        # 返回结果！
        if sign == sign2:
            return True
        else:
            return False


